<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="办公楼名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入办公楼名称" :clearable="true" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="办公区" prop="areaId">
            <el-select v-model="formData.areaId" placeholder="请输入办公区">
              <el-option
                v-for="dict in areaList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="建筑面积" prop="buildingArea">
            <InputNumber
              type="decimal"
              v-model="formData.buildingArea"
              placeholder="请输入建筑面积"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总楼层" prop="floorCount">
            <el-input v-model="formData.floorCount" placeholder="请输入总楼层" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-tabs v-model="tabActiveName" type="card">
      <el-tab-pane label="楼层" name="floor">
        <el-form-item>
          <el-button @click="clickAddFloor">添加楼层</el-button>
          <el-button @click="clickDeleteFloor">删除楼层</el-button>
        </el-form-item>
        <Table
          :columns="floorColumns"
          height="230"
          :data="formData.buildingFloors"
          save-key="OfficeBuildingFloorEdit"
          :row-style="floorRowStyle"
          @row-click="handleFloorRowClick"
        >
          <template #name="{ row }">
            <el-input v-model="row.name" />
          </template>
          <template #remark="{ row }">
            <el-input v-model="row.remark" />
          </template>
        </Table>
      </el-tab-pane>
      <el-tab-pane label="单元" name="unit">
        <el-form-item>
          <el-button @click="clickAddUnit">添加单元</el-button>
          <el-button @click="clickDeleteUnit">删除单元</el-button>
        </el-form-item>
        <Table
          :columns="unitColumns"
          height="230"
          :data="formData.buildingUnits"
          save-key="OfficeBuildingUnitEdit"
          :row-style="unitRowStyle"
          @row-click="handleUnitRowClick"
        >
          <template #name="{ row }">
            <el-input v-model="row.name" />
          </template>
          <template #remark="{ row }">
            <el-input v-model="row.remark" />
          </template>
        </Table>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup name="OfficeBuildingEdit" lang="ts">
import * as OfficeBuildingApi from '@/api/office/building'
import * as OfficeAreaApi from '@/api/area/officeArea'
import * as OfficeBuildingModel from '@/model/office/building/OfficeBuilding'
import * as OfficeBuildingFloorModel from '@/model/office/building/OfficeBuildingFloor'
import * as OfficeBuildingUnitModel from '@/model/office/building/OfficeBuildingUnit'
interface OfficeBuildingFloorEdit extends OfficeBuildingFloorModel.OfficeBuildingFloor {
  operateType: string
}

interface OfficeBuildingUnitEdit extends OfficeBuildingUnitModel.OfficeBuildingUnit {
  operateType: string
}

interface OfficeBuildingEidt extends OfficeBuildingModel.OfficeBuilding {
  buildingFloors: OfficeBuildingFloorEdit[]
  buildingUnits: OfficeBuildingUnitEdit[]
}
let formType = ''
const tabActiveName = ref('floor')
const message = useMessage()
const { t } = useI18n()
const areaList = ref()
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const formData = ref<OfficeBuildingEidt>({
  id: undefined,
  name: '',
  areaId: undefined,
  buildingArea: 0,
  floorCount: 0,
  officeBuildingArea: 0,
  serviceBuildingArea: 0,
  deviceBuildingArea: 0,
  attachBuildingArea: 0,
  technologyBuildingArea: 0,
  buildingFloors: [],
  buildingUnits: []
})
const formRules = reactive({
  name: [{ required: true, message: '请输入办公楼名称', trigger: 'blur' }],
  areaId: [{ required: true, message: '请选择办公区', trigger: 'blur' }]
})
const floorTableCurrentRow = ref()
const unitTableCurrentRow = ref()
const floorColumns = [
  {
    label: '名称',
    prop: 'name',
    slot: 'name'
  },
  {
    label: '备注',
    prop: 'remark',
    slot: 'remark'
  }
]

const unitColumns = [
  {
    label: '名称',
    prop: 'name',
    slot: 'name'
  },
  {
    label: '备注',
    prop: 'remark',
    slot: 'remark'
  }
]
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  areaList.value = await OfficeAreaApi.simpleList()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OfficeBuildingApi.singleGet(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    areaId: undefined,
    buildingArea: 0,
    floorCount: 0,
    officeBuildingArea: 0,
    serviceBuildingArea: 0,
    deviceBuildingArea: 0,
    attachBuildingArea: 0,
    technologyBuildingArea: 0,
    buildingFloors: [],
    buildingUnits: []
  }
  tabActiveName.value = 'floor'
  formRef.value?.resetFields()
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  let isDuplicateFloor = false,
    isDuplicateUnit = false
  let floorNames: string[] = []
  formData.value.buildingFloors.forEach((floor) => {
    if (floor.operateType != 'delete') {
      if (floorNames.indexOf(floor.name) >= 0) {
        isDuplicateFloor = true
      } else {
        floorNames.push(floor.name)
      }
    }
  })
  if (isDuplicateFloor) {
    message.error('存在重复名称的楼层')
    return
  }
  let unitNames: string[] = []
  formData.value.buildingUnits.forEach((unit) => {
    if (unit.operateType != 'delete') {
      if (unitNames.indexOf(unit.name) >= 0) {
        isDuplicateFloor = true
      } else {
        unitNames.push(unit.name)
      }
    }
  })
  if (isDuplicateUnit) {
    message.error('存在重复名称的单元')
    return
  }

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OfficeBuildingEidt
    if (formType === 'create') {
      await OfficeBuildingApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await OfficeBuildingApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

watch(
  () => formData.value.buildingFloors,
  (newBuildingFloors) => {
    formData.value.floorCount = newBuildingFloors.filter(
      (floor) => floor.operateType != 'delete'
    ).length
  },
  { deep: true }
)

/** table行的style的回调方法 */
const floorRowStyle = ({ row }) => {
  if (row?.operateType == 'delete') {
    return { display: 'none' }
  } else return {}
}

/** table行点击事件 */
const handleFloorRowClick = (row) => {
  floorTableCurrentRow.value = row
}

/** table行的style的回调方法 */
const unitRowStyle = ({ row }) => {
  if (row?.operateType == 'delete') {
    return { display: 'none' }
  } else return {}
}

/** table行点击事件 */
const handleUnitRowClick = (row) => {
  unitTableCurrentRow.value = row
}

const clickAddFloor = () => {
  formData.value.buildingFloors.push({
    id: undefined,
    name: (formData.value.buildingFloors.length + 1).toString() + '层',
    buildingId: formType === 'create' ? undefined : formData.value.id,
    remark: '',
    operateType: 'new'
  })
}

const clickDeleteFloor = () => {
  if (formType === 'create' || floorTableCurrentRow.value.id == undefined) {
    const index = formData.value.buildingFloors.indexOf(floorTableCurrentRow.value)
    formData.value.buildingFloors.splice(index, 1)
  } else {
    floorTableCurrentRow.value.operateType = 'delete'
  }
}

const clickAddUnit = () => {
  formData.value.buildingUnits.push({
    id: undefined,
    name: (formData.value.buildingUnits.length + 1).toString() + '单元',
    buildingId: formType === 'create' ? undefined : formData.value.id,
    remark: '',
    operateType: 'new'
  })
}

const clickDeleteUnit = () => {
  if (formType === 'create' || unitTableCurrentRow.value.id == undefined) {
    const index = formData.value.buildingUnits.indexOf(unitTableCurrentRow.value)
    formData.value.buildingUnits.splice(index, 1)
  } else {
    unitTableCurrentRow.value.operateType = 'delete'
  }
}
</script>
